package com.zg.http;

import javax.annotation.Priority;
import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.ResourceInfo;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 根据用户角色控制访问权限 Created by tanzhibo on 2016/8/18.
 */
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

	@Context
	private ResourceInfo resourceInfo;

	@Context
	private HttpServletRequest request;

	@Context
	private HttpServletResponse response;

	//TODO 添加CSRF防御
	@Override
	public void filter(ContainerRequestContext requestContext) throws IOException {
		Class<?> className = resourceInfo.getResourceClass();
		Method method = resourceInfo.getResourceMethod();
		if (className.isAnnotationPresent(PermitAll.class) || method.isAnnotationPresent(PermitAll.class)) {
			return;
		}

		Object admin = request.getSession().getAttribute("admin");
		if (null == admin) {
			requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
			return;
		}
	}
}